from flask import Blueprint,request,jsonify
from functools import wraps
import hashlib

def sha256_hash(value: str) -> str:
    """计算字符串的 SHA256 哈希，返回十六进制字符串"""
    return hashlib.sha256(value.encode("utf-8")).hexdigest()


def login_required(f):
    """登录验证装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        auth_header = request.headers.get("Authorization")
        if not auth_header:
            return jsonify({"error": "Missing Authorization header"}), 401

        parts = auth_header.split()
        if len(parts) != 2 or parts[0].lower() != "bearer":
            return jsonify({"error": "Invalid Authorization format"}), 401

        token = parts[1]

        # 检查 token 是否有效
        if token != sha256_hash('admin'):
            return jsonify({"error": "Invalid Authorization token"}), 401
        return f(*args, **kwargs)
    return decorated_function